package com.ad.pages;

import java.util.List;

import org.apache.tapestry5.annotations.Id;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.ad.base.AbstractPage;
import com.ad.helper.Css4TipDiv;
import com.ad.hibernate.Tip;
import com.ad.hibernate.TipType;
import com.ad.services.ITipManagerService;
import com.ad.services.IUserManagerService;
import com.ad.system.Common;
import com.ad.system.State;

public class Publish extends AbstractPage {

	@Property
	private String type;

	@Property
	private List<TipType> tipTypeList;

	@Property
	private TipType tipType = new TipType();

	@Property
	private Tip tip = new Tip();

	@SessionState
	private State state;

	@Property
	private String typeList;

	@SuppressWarnings("unused")
	@Property
	private String white = Css4TipDiv.WHITE_X;

	@SuppressWarnings("unused")
	@Property
	private String gray = Css4TipDiv.GRAY_X;

	@SuppressWarnings("unused")
	@Property
	private String orange = Css4TipDiv.ORANGE_X;

	@SuppressWarnings("unused")
	@Property
	private String yellow = Css4TipDiv.YELLOW_X;

	@Inject
	@Id("tipManagerService")
	private ITipManagerService tipManagerService;

	@Property
	private String nickName;

	@Inject
	@Id("UserManagerService")
	private IUserManagerService UserManagerService;

	protected void setupRender() {
		super.setupRender();
		if (!Common.isEmpty(state.getEmail())) {
			tip.setCreator(state.getEmail());
		}else{
			tip.setCreator("kids");
		}
		nickName = UserManagerService.getUserNameByEmail(state.getEmail());
		tipTypeList = tipManagerService.getType();
		generateTypeList();

	}

	private void generateTypeList() {
		StringBuffer typeBuffer = new StringBuffer();
		for (int i = 0; i < tipTypeList.size() - 1; i++) {
			typeBuffer.append(tipTypeList.get(i).getId()).append("=").append(
					tipTypeList.get(i).getCategoriesName()).append(",");
		}
		typeBuffer.append(tipTypeList.get(tipTypeList.size() - 1).getId())
				.append("=").append(
						tipTypeList.get(tipTypeList.size() - 1)
								.getCategoriesName());
		typeList = typeBuffer.toString();
	}

	Object onSuccess() {
		tip.setContent(tip.getContent().trim());
		tipManagerService.insert(tip);
		return "home";
	}

}
